<?php

namespace app\controllers;
use yii\caching\Cache;
use yii\db\Query;
use yii\web\Controller;


class ApiLoginController extends Controller{


    //授权登录
    private $token;
    private $appId;
    private $appSecret;
    public $enableCsrfValidation = false;

    public function init(){
        $info=(new Query())->select('*')->from('yii_wxapp')->one();
        $this->appId=$info['AppID'];
        $this->appSecret=$info['AppSecret'];
    }


    //登录
    public function actionLogin(){
        $post=\Yii::$app->request->post();
        //微信登录 获取session_key
        $session = $this->wxlogin($post['code']);
        if (isset($session['code'])){
            return json_encode(['code'=>0,'msg'=>$session['msg']]);
        }
        unset($post['code']);
        $post['openid']=$session['openid'];
        // 自动注册用户
        $user_id = $this->register($post);
        // 生成token (session3rd)
        $this->token = $this->token($post['openid']);
        $post['user_id']=$user_id;
        // 记录缓存, 7天
        $cache =\Yii::$app->cache;
        $cache->set($this->token,$post,86400*7);

        return json_encode(['code'=>1,'user_id'=>$user_id,'token'=>$this->token]);
    }


    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code){
        // 获取当前小程序信息
        if ($this->appId=="" || $this->appSecret=="") {
            return ['code'=>-1,'msg'=>'请到[小程序-参数设置] 填写appid和appSecret'];
        }
        // 微信登录 (获取session_key)
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $url.= 'appid='.$this->appId.'&secret='.$this->appSecret.'&js_code='.$code.'&grant_type=authorization_code';
        $result = json_decode($this->get($url),true);

        if (isset($result['errcode'])) {
            return ['code' => 0, 'msg' => $result['errmsg']];;
        }

        return $result;
    }


    /**
     * 模拟GET请求 HTTPS的页面
     * @param string $url 请求地址
     * @return string $result
     */
    public function get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid){
        return md5($openid . 'token_salt');
    }




    /**
     * 自动注册用户
     */
    private function register($post){
        $post['nickName'] = preg_replace('/[\xf0-\xf7].{3}/', '', $post['nickName']);

        $check=(new Query())->select('user_id')->from('yii_user')->where(['openid'=>$post['openid']])->one();
        if(!$check){
            $post['create_time']=time();
            $post['update_time']=time();
            \Yii::$app->db->createCommand()->insert('yii_user',$post)->execute();
            $user_id =(int)\Yii::$app->db->getLastInsertID();
            if ($user_id<1) {
                return json_encode(['code'=>-1,'msg' => '用户注册失败']);
            }
            return $user_id;
        }else{
            $post['update_time']=time();
            \Yii::$app->db->createCommand()->update('yii_user',$post,['user_id'=>$check['user_id']])->execute();
            return (int)$check['user_id'];
        }
    }

}
